<template>
  <BasicModal
    :title="title"
    :width="800"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top: 5%; height: 80%; overflow-y: hidden"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { formSchema } from '../application.data';
  import { createApplication, updateApplication } from '/@/api/application';

  const emit = defineEmits(['register', 'success']);

  const isUpdate = ref(false);
  const recordId = ref('');

  const title = computed(() => {
    return isUpdate.value ? '修改' : '新增';
  });

  const [registerForm, { setFieldsValue, validate, updateSchema, resetFields }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { closeModal, setModalProps }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (isUpdate.value) {
      recordId.value = data.record.id;
      updateSchema({ field: 'code', dynamicDisabled: true });
      setFieldsValue({
        ...data.record,
      });
    } else {
      resetFields();
      updateSchema({ field: 'code', dynamicDisabled: false });
    }
  });

  const handleSubmit = async () => {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      if (isUpdate.value) {
        await updateApplication({
          id: recordId.value,
          ...values,
        });
        message.success('修改应用成功');
      } else {
        await createApplication(values);
        message.success('创建应用成功');
      }
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };

  const handleCancel = () => {
    closeModal();
  };
</script>
